package com.zxl.security.core.social.qq.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /** 这里不需要去处理access_token，内置在发restTemplate请求的时候，拦截器帮我们在后面拼接access_token参数过去 */
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me";
    private static final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
    private String appId;
    private String openId;
    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String assessToken, String appId) {
        super(assessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);// 使用ACCESS_TOKEN_PARAMETER会将我们的access_token自动拼接到请求上
        this.appId = appId;
        // 返回数据格式：callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
        String result = getRestTemplate().getForObject(URL_GET_OPENID, String.class);
        logger.info("收到QQ授权返回的全部信息 = {}", result);
        JsonNode jsonNode;
        try {
            jsonNode = objectMapper.readTree(result.substring(result.indexOf("{"), result.lastIndexOf("}")));
        } catch (IOException e) {
            throw new RuntimeException("解析QQ授权返回的openid信息错误");
        }
        this.openId = jsonNode.get("openid").asText(null);
        String clientId = jsonNode.get("client_id").asText(null);
        logger.info("获取access_token时，返回的AppID = " + clientId);
        logger.info("收到QQ返回的openid = {}", this.openId);
    }

    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        // 查看源代码第一个添加的就是StringHttpMessageConverter，默认是处理ISO-8859-1字符集的，我们进行移除，定义我们需要的字符集格式转化
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }

    @Override
    public QQUserInfo getUserInfo() {
        String url = String.format(URL_GET_USER_INFO, appId, openId);
        QQUserInfo userInfo = getRestTemplate().getForObject(url, QQUserInfo.class);
        userInfo.setOpenId(openId);
        logger.info("收到QQ返回的用户信息 = {}", userInfo.toString());
        return userInfo;
    }
}
